<template>
  <div>
    <van-nav-bar
    title="登录"
    left-arrow
    @click-left="$router.back()"
    />
    <van-form @submit="login">
      <van-field
        v-model="mobile"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        label="验证码"
        placeholder="请输入验证码"
        required
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="loading"
          :disabled="loading"
          round
          block
          type="info"
          native-type="submit"
          >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      mobile: '15907086863',
      code: '246810',
      loading: false,
      rules: {
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式错误'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },
  methods: {
    // 这样写如果登录失败会直接报错,因为await只会等到成功后的结果(封装后)
    //   async  login () {
    //     const res = await login(this.mobile, this.code)
    //     console.log(res.data)
    //   }

    ...mapMutations('user', ['setToken']),
    // 封装api文件发送请求
    async login () {
      this.loading = true
      try {
        const res = await login(this.mobile, this.code)
        this.setToken(res.data)
        this.$toast.success('登录成功')
        this.$router.push('/')
      } catch {
        this.$toast.fail('登录失败')
      }
      this.loading = false
    }
  }
}

</script>

<style>

</style>
